package com.yxuan.springboot.service.impl;

import com.yxuan.springboot.mapper.KamilsMapper;
import com.yxuan.springboot.model.UserVip;
import com.yxuan.springboot.service.UserVipService;
import com.yxuan.springboot.util.MD5Util;
import com.yxuan.springboot.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yxuan.springboot.model.Kamils;
import com.yxuan.springboot.service.KamilsService;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 
 * @author zchao
 *    Kamils业务层实现类
 * @date 2024-05-14 19:58:05
 */
@Slf4j
@Service
@Transactional
public class KamilsServiceImpl extends BaseServiceImpl<Kamils> implements KamilsService {

    @Autowired
    private KamilsMapper kamilsMapper;

    @Autowired
    private UserVipService userVipService;

    @Override
    public Result activeKamil(Map kamils) throws Exception {

        String userId = kamils.get("userId").toString();
        String knumber = kamils.get("knumber").toString();
        String kamil = kamils.get("kamil").toString();
        //md5加密后比较是否一致
        String s = MD5Util.string2MD5(kamil);

        Kamils k = new Kamils();
        k.setKnumber(knumber);
        k.setKamil(s);
        Kamils targetK = kamilsMapper.queryObjectByPramas(k);
        if(targetK==null){
            return new Result(201,"卡密错误");
        }
        //卡密验证成功==>验证卡是否到期
        Date expireTime = targetK.getExpireTime();
        /*
        如果当前日期在参数日期之前，则返回一个负数；
        如果当前日期和参数日期相等，则返回0；
        如果当前日期在参数日期之后，则返回一个正数。
        */
        Date nowaDay = new Date();
        if(expireTime==null){
            return new Result(201,"卡密已过期");
        }else {
            if (nowaDay.compareTo(expireTime) >= 0) {
                //已过期
                return new Result(201,"卡密已过期");
            }
            //未过期，将状态改为以激活
            String ktype = targetK.getKtype();
            k = new Kamils();
            k.setId(targetK.getId());
            k.setKuseState("已使用");
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date activeTime = formatter.parse(formatter.format(date));
            k.setActiveTime(activeTime);
            kamilsMapper.update(k);

            //修改对应userId的uservip信息
            //找到当前用户vip信息
            UserVip userVip = new UserVip();
            userVip.setUserId(Integer.valueOf(userId));
            UserVip userVip1 = userVipService.findObjectByPramas(userVip);
            //获取当前用户vip等级
            String vipRankMyself = userVip1.getVipRank();
            //获取gpt使用次数
            Integer getGptTimes = 0;
            if (userVip1.getGptTimes() == null || userVip1.getGptTimes().equals("")) {
                getGptTimes = 0;
            } else {
                getGptTimes = Integer.valueOf(userVip1.getGptTimes());
            }
            //获取今日修改用户信息次数
            Integer getInfoUpdTimes = 0;
            if (userVip1.getInfoUpdTimes() == null || userVip1.getInfoUpdTimes().equals("")) {
                getInfoUpdTimes = 0;
            } else {
                getInfoUpdTimes = Integer.valueOf(userVip1.getInfoUpdTimes());
            }
            //获取今日测录取率次数
            Integer getProbabilityTimes = 0;
            if (userVip1.getProbabilityTimes() == null || userVip1.getProbabilityTimes().equals("")) {
                getProbabilityTimes = 0;
            } else {
                getProbabilityTimes = Integer.valueOf(userVip1.getProbabilityTimes());
            }

//根据购买的商品种类对gpt使用次数，今日修改用户信息次数，今日测录取率次数进行修改
            System.out.println("//根据购买的商品种类对gpt使用次数，今日修改用户信息次数，今日测录取率次数进行修改");
            switch (ktype) {
                case "日会员":
                    userVip.setVipRank("1");
                    userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                    userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 2));
                    userVip.setGptTimes(String.valueOf(getGptTimes + 5));
                    break;
                //这里对周会员进行修改为月会员
                case "月会员":
                    userVip.setVipRank("2");
                    userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                    userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 3));
                    userVip.setGptTimes(String.valueOf(getGptTimes + 50));
                    break;
                //这里对月会员进行修改为年会员
                case "年会员":
                    userVip.setVipRank("3");
                    userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                    userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 5));
                    userVip.setGptTimes(String.valueOf(getGptTimes + 120));
                    break;
                default:
                    userVip.setVipRank("1");
                    userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                    userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 2));
                    userVip.setGptTimes(String.valueOf(getGptTimes + 5));
                    break;
            }

            if(Integer.parseInt(userVip.getVipRank()) < Integer.parseInt(vipRankMyself)) {
                userVip.setVipRank(vipRankMyself);
            }

            Date nows = new Date(System.currentTimeMillis());
//设置会员到期时间
            //这里是如果之前没有买过任何会员的情况
            System.out.println("这里是如果之前没有买过任何会员的情况");
            if (userVip1.getExpirationTime() == null || userVip1.getExpirationTime().compareTo(nows) < 0) {
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedNow = now.format(formatter3);
                System.out.println("当前时间：" + formattedNow);
                LocalDateTime after10Minutes = null;
                if (ktype.equals("日会员")) {
                    after10Minutes = now.plusMinutes(60 * 24);

                }
                //这里对周会员进行修改为月会员
                else if (ktype.equals("月会员")) {
                    after10Minutes = now.plusMinutes(60 * 24 * 30);

                }
                //这里对月会员进行修改为年会员
                else if (ktype.equals("月会员")) {
                    after10Minutes = now.plusMinutes(60 * 24 * 365);

                } else {
                    after10Minutes = now.plusMinutes(60 * 24);

                }
                String formattedAfter10Minutes = after10Minutes.format(formatter3);
                Date expirationTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(formattedAfter10Minutes);
                userVip.setExpirationTime(expirationTime);
            } else {
                //如果之前有买过会员的情况
                System.out.println("如果之前有买过会员的情况");
                Date date2 = userVip1.getExpirationTime();

                // 使用Calendar类将date转换为Calendar对象
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date2);

                // 在Calendar对象上增加24小时
                if (ktype.equals("日会员")) {
                    calendar.add(Calendar.HOUR_OF_DAY, 24);
                } else if (ktype.equals("月会员")) {
                    calendar.add(Calendar.HOUR_OF_DAY, 24 * 30);
                } else if (ktype.equals("年会员")) {
                    calendar.add(Calendar.HOUR_OF_DAY, 24 * 365);
                } else {
                    calendar.add(Calendar.HOUR_OF_DAY, 24);
                }
                // 将Calendar对象转换为Date对象
                Date newDate = calendar.getTime();

                // 使用DateTimeFormatter类将Date对象格式化为指定格式的字符串
                DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedNewDate = LocalDateTime.ofInstant(newDate.toInstant(), ZoneId.systemDefault()).format(formatter2);
                // 使用SimpleDateFormat类将字符串转换为Date对象
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date expirationTime = null;
                try {
                    expirationTime = sdf.parse(formattedNewDate);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 调用setExpirationTime方法
                userVip.setExpirationTime(expirationTime);
            }
            log.info("修改userVip");
            userVipService.upd(userVip);
            log.info("修改完成");
            return new Result(200,"会员激活成功");
        }
    }
}
